package client.comm.baoding.ui.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Response

class HmSellViewModel(app: Application) : MiddleVm(app) {

    val userInfo: UserInfo? by lazy {
        StoreUtil.getBean(getApplication())
    }
    val callDs = MutableLiveData<JsonResult<Ret>>()
    val isShowing = MutableLiveData<Boolean>()

    val txNumDs = MutableLiveData<String>()
    val zzPwdDs = MutableLiveData<String>()

    /**
     */
    fun okSell() {

        if (zzPwdDs.value.isNullOrEmpty() || txNumDs.value.isNullOrEmpty()) {
            toast("不得为空")
            return
        }
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(zzPwdDs.value!!)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: JsonResult<Ret>? = null
                it?.body()?.let {
                    if (it.isSuccess) {
                        val ret = server.hm_trade(txNumDs.value!!, 2)
                        emm = ret?.body()
                    } else {
                        emm = JsonResult<Ret>().apply {
                            message = it.message
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
//                    toast(cause.message)
                    toast("网络错误")
                }
            }.collectLatest {
                callDs.value = it
            }
        }
    }

}